package com.postsuperman.proxypool.api;

import com.postsuperman.proxypool.common.Response;
import com.postsuperman.proxypool.common.enums.StatusEnum;
import com.postsuperman.proxypool.dao.ProxyDAO;
import com.postsuperman.proxypool.pojo.HttpProxy;
import com.postsuperman.proxypool.pojo.PageInfo;
import com.postsuperman.proxypool.pojo.dto.QueryDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author ： Lwl postserupman
 * @Description TODO
 * @Date 2019/2/27 12:06
 * @Version 1.0
 */
@Api("代理API")
@RestController
@RequestMapping(value = "ProxyApi")
public class ProxyApi {

    @Autowired
    private ProxyDAO proxyDAO;

    /**
     * 随机获取一个代理
     *
     * @return
     */
    @ApiOperation("随机获取一个代理")
    @GetMapping("random")
    public Object random() {
        HttpProxy proxy = this.proxyDAO.getRandomByOne();
        if (StringUtils.isEmpty(proxy)) {
            return Response.error(StatusEnum.NOT_FOUND);
        }
        return Response.success(proxy);
    }

    /**
     * 手动录入代理
     *
     * @param ip   代理
     * @param port 端口
     * @return
     */
    @ApiOperation("手动录入代理")
    @PostMapping("/add")
    public Object add(@RequestParam(name = "ip") String ip, @RequestParam(name = "port") Integer port) {
        if (StringUtils.isEmpty(ip) || port == null) {
            return Response.error(StatusEnum.PARAMS_ERROR);
        }
        HttpProxy httpProxy = new HttpProxy();
        httpProxy.setIp(ip);
        httpProxy.setPort(port);
        return this.proxyDAO.insert(httpProxy);
    }

    /**
     * 分页获取当前代理池的所有代理
     *
     * @param queryDTO
     * @return
     */
    @ApiOperation("分页条件查询代理池")
    @GetMapping("/getList")
    public Object list(QueryDTO queryDTO) {
        PageInfo pageInfo = new PageInfo();
        long count = this.proxyDAO.getTotalCount();
        if (count > 0) {
            pageInfo.setPageNum(queryDTO.getPageNum());
            pageInfo.setPageSize(queryDTO.getPageSize());
            pageInfo.setTotal((int) count);

            List<HttpProxy> list = this.proxyDAO.findByCond(queryDTO, false);
            pageInfo.setList(list);
        }
        return Response.success(pageInfo);
    }

    /**
     *
     * @return
     */
    @ApiOperation("findAll")
    @GetMapping("/findAll")
    public Object findAll() {
        List<HttpProxy> proxies = this.proxyDAO.findAll();
        return Response.success();
    }
}
